const { createCanvas, loadImage } = require("canvas");
const fs = require("fs");

async function main() {
  const myimg = await loadImage("before.jpg");
  const canvas = createCanvas(myimg.width, myimg.height);
  const ctx = canvas.getContext("2d");
  ctx.drawImage(myimg, 0, 0);
  let imgData = ctx.getImageData(0, 0, myimg.width, myimg.height);
  let data = imgData.data;
  console.log(data);
  for (let i = 0; i < data.length; i += 4) {
    var avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
    //var avg = data[i]* 0.3 + data[i+1]* 0.59 + data[i+2]* 0.11
    var pct = Math.abs(avg - 127) / 127;
    // pct = mat
    var ori = 1;
    if ((i / 4) % myimg.width < myimg.width / 2) {
      data[i] = data[i] * pct;
      data[i + 1] = data[i + 1] * pct;
      data[i + 2] = data[i + 2] * ori * Math.sqrt(pct);
    } else {
      data[i] *= ori;
      data[i + 1] = data[i + 1] * pct;
      data[i + 2] = data[i + 2] * pct;
    }
  }
  ctx.putImageData(imgData, 0, 0);
  canvas.createJPEGStream().pipe(fs.createWriteStream("abc.jpg"));
}

main();
